﻿using System;
using System.Web.UI.WebControls;
using System.Linq;
using System.Collections.Generic;
using Service;
using Data.Entity;

namespace ECommerce.Administration.Controls
{
	public partial class ProductList : AdminBaseUsercontrol
	{
		private Service.IProductService _ProductService;
		private Service.ICategoryService _CategoryService;
		private IEnumerable<Product> _DataSource;
		private int _TotalRecords;

		public int PageIndex
		{
			get
			{
				if (ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = DataSource;

				if (data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if (totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if (totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if (totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return this.GridProducts.PageSize;
			}
			set
			{
				this.GridProducts.PageSize = value;
			}
		}

		public int CategoryID
		{
			get
			{
				if (DDLCategory.SelectedIndex > 0)
				{
					return int.Parse(DDLCategory.SelectedValue);
				}
				else
				{
					return 0;
				}
			}
		}

		public string SearchKeyword
		{
			get
			{
				return TextProductName.Text.Trim();
			}
		}

		public IEnumerable<Product> DataSource
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				if (_ProductService == null)
				{
					_ProductService = new ProductService();
				}

				if (CategoryID > 0)
				{
					if (string.IsNullOrEmpty(SearchKeyword))
					{
						_DataSource = _ProductService.GetProductsByCategory(CategoryID, pageIndex, pageSize, out totalRecords);

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
					else
					{
						_DataSource = _ProductService.GetProductsByCategory(CategoryID, pageIndex, pageSize, out totalRecords);

						if (_DataSource != null)
						{
							_DataSource = _DataSource.Where(p => p.Name.Contains(SearchKeyword));

							if (_DataSource != null)
							{
								totalRecords = _DataSource.Count();
							}
							else
							{
								totalRecords = 0;
							}
						}

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
				}
				else
				{
					if (SiteContext.Current.WorkingLanguage == null)
					{
						this.TotalRecords = 0;
						return null;
					}

					int currentLanguageID = SiteContext.Current.WorkingLanguage.LanguageId;

					this.Page.Title = GetLocalResourceString("Ecommerce.PageTitle.Products");

					if (string.IsNullOrEmpty(SearchKeyword))
					{
						_DataSource = _ProductService.GetProductsByLanguage(currentLanguageID, pageIndex, pageSize, out totalRecords);

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
					else
					{
						_DataSource = _ProductService.GetProductsByLanguage(currentLanguageID, pageIndex, pageSize, out totalRecords);

						if (_DataSource != null)
						{
							_DataSource = _DataSource.Where(p => p.Name.Contains(SearchKeyword));

							if (_DataSource != null)
							{
								totalRecords = _DataSource.Count();
							}
							else
							{
								totalRecords = 0;
							}
						}

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
				}
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~Administration/AdminLogin.aspx");
			}

			if (!IsPostBack)
			{
				this.LinkButtonFirstPage.Text = GetLocalResourceString("ProductList.LinkButtonFirstPageText");
				this.LinkButtonLastPage.Text = GetLocalResourceString("ProductList.LinkButtonLastPageText");
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				ButtonSearch.Text = GetLocalResourceString("Admin.SearchButton.Text");
			}

			BindCategory();

			BindProducts();

			var currentPageIndex = this.PageIndex;
			var totalPages = TotalPages;

			if (currentPageIndex == 0 || PageSize <= 1)
			{
				LinkButtonFirstPage.Enabled = false;
			}
			else
			{
				LinkButtonFirstPage.Enabled = true;
			}

			if (currentPageIndex == totalPages - 1 || totalPages <= 1)
			{
				LinkButtonLastPage.Enabled = false;
			}
			else
			{
				LinkButtonLastPage.Enabled = true;
			}

			// set pager index links
			List<PagerIndex> indexs = new List<PagerIndex>();

			if (totalPages <= 10)
			{
				for (int i = 1; i <= totalPages; i++)
				{
					indexs.Add(new PagerIndex(i.ToString()));
				}
			}
			else if (totalPages > 10)
			{
				if (((currentPageIndex / 10) * 10 + 10) > totalPages)
				{
					for (int i = (currentPageIndex / 10) * 10 + 1; i <= totalPages; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
				else if (((currentPageIndex / 10) * 10 + 10) <= totalPages)
				{
					for (int i = (currentPageIndex / 10) * 10 + 1; i <= (currentPageIndex / 10) * 10 + 10; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
			}

			this.RepeaterPageIndex.DataSource = indexs;
			this.RepeaterPageIndex.DataBind();

			//this.LabelTotalPages.Text = totalPages.ToString();
			//this.LabelTotalRecords.Text = TotalRecords.ToString();
			//this.LabelTotalPages1.Text = totalPages.ToString();
			//this.LabelTotalRecords1.Text = TotalRecords.ToString();

			// disenabel the current pagerindex link
			if (RepeaterPageIndex.TemplateControl.Controls.Count > 1)
			{
				for (int i = 0; i < RepeaterPageIndex.Items.Count; i++)
				{
					LinkButton thePagerIndexLink = RepeaterPageIndex.Items[i].FindControl("LinkButtonPageIndex") as LinkButton;

					if (thePagerIndexLink.Text.Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink.Enabled = false;
					}
				}
			}
		}

		protected void ButtonSearch_Click(object sender, EventArgs e)
		{
			this.PageIndex = 0;

			//BindProducts();
		}

		protected void GridProducts_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[1].Text = GetLocalResourceString("Admin.ProductList.NameHeader");
				e.Row.Cells[2].Text = GetLocalResourceString("Admin.ProductList.ListPriceHeader");
				e.Row.Cells[3].Text = GetLocalResourceString("Admin.ProductList.CreatedOnHeader");
				e.Row.Cells[4].Text = GetLocalResourceString("Admin.ProductList.UpdatedOnHeader");
				e.Row.Cells[5].Text = GetLocalResourceString("Admin.ProductList.QuantityHeader");
				e.Row.Cells[6].Text = GetLocalResourceString("Admin.ProductList.PublishedHeader");
				e.Row.Cells[7].Text = GetLocalResourceString("Admin.ProductList.RecommendHeader");
				e.Row.Cells[8].Text = GetLocalResourceString("Admin.ProductList.ShowOnHomePageHeader");
			}

			if (e.Row.DataItem != null)
			{
				var item = e.Row.DataItem as Data.Entity.Product;

				HyperLink HyperLinkProductName = e.Row.FindControl("HyperLinkProductName") as HyperLink;

				HyperLinkProductName.Text = item.Name;
				HyperLinkProductName.NavigateUrl = "~/Administration/EditProduct.aspx?productid=" + item.ProductID.ToString();
			}
		}

		private void BindProducts()
		{
			var data = DataSource;

			if (data != null)
			{
				data = data.OrderByDescending(exp => exp.CreatedOn);
			}

			GridProducts.DataSource = data;
			GridProducts.DataBind();
		}

		private void BindCategory()
		{
			if (_CategoryService == null)
			{
				_CategoryService = new CategoryService();
			}

			if (SiteContext.Current != null)
			{
				var lan = SiteContext.Current.WorkingLanguage;

				if (lan != null)
				{
					var languageID = lan.LanguageId;

					var categories = _CategoryService.GetCategoryByLanguage(languageID);

					DDLCategory.Items.Clear();

					ListItem item0 = new ListItem("", "0");

					DDLCategory.Items.Add(item0);

					if (categories != null)
					{
						foreach (var item in categories)
						{
							ListItem li = new ListItem(item.CategoryName, item.CategoryID.ToString());

							DDLCategory.Items.Add(li);
						}
					}
				}
			}
		}

		public void DeleteSelectedProduct()
		{
			if (_ProductService == null)
			{
				_ProductService = new Service.ProductService();
			}

			foreach (System.Web.UI.WebControls.GridViewRow rowItem in GridProducts.Rows)
			{
				var chBox = rowItem.FindControl("cbProduct") as CheckBox;
				var hfProductID = rowItem.FindControl("hfProductId") as HiddenField;

				bool isChecked = chBox.Checked;
				int productID = int.Parse(hfProductID.Value);

				if (isChecked)
				{
					_ProductService.DeleteProduct(productID);
				}
			}

			//BindProducts();
		}

		protected void LinkButtonPaging_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "FirstPage":
					{
						PageIndex = 0;

						//BindProducts();
					}
					break;
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						//BindProducts();
					}
					break;
				case "LastPage":
					{
						PageIndex = TotalPages - 1;

						//BindProducts();
					}
					break;
			}
		}
	}
}